const http = require("http");
// 引入WebSocket库
const WebSocketServer = require("websocket").server;
// 创建一个HTTP Server
const httpServer = http.createServer((request, response) => {
  response.writeHead(404);
  response.end();
});

const webServer = new WebSocketServer({
  httpServer,
  autoAcceptConnections: true,
});

webServer.on("connect", (connection) => {
  connection.on("message", (message) => {
    console.log(">>message", message);
    if (message.type === "utf8") {
      const data = { content: "自动回复", date: new Date() };
      connection.sendUTF(JSON.stringify(data));
    }
  });
  connection.on("close", (code, desc) => {
    console.log(
      "[" + new Date() + "] Peer " + connection.remoteAddress + " desc."
    );
  });
  process.stdin.on("data", (data) => {
    let temp = data.toString().trim();
    temp = { content: data, date: new Date().getDay() };
    connection.sendUTF(JSON.stringify(temp));
  });
});

httpServer.listen(2811, () => {
  console.log("[" + new Date() + "]　server is listening on port 2811");
});
